#!/bin/bash
#
# Mojohost
# Script: mailadd.sh
#
# Description: Adds new emails/aliases to sendmail.
#
# Requires: sendmail must be installed and running.
#
# Author: Gary Locke


# TODO:
# -- Make sure ports are open to the world
# -- Test email account once created
# -- Avoid creating duplicate accounts
# -- Get alias creation working


# Variables for sendmail file paths.
USER_FILE=/etc/mail/virtusertable
ALIAS_FILE=/etc/aliases

# Variables to add color to stdout.
RED="\033[1;31m"
GREEN="\033[1;32m"
COLOR_RESET="\033[0m"
BOLD=`tput bold`
NORMAL=`tput sgr0`

getEmailAddress() {
read -e -p "${BOLD}Enter email address:${NORMAL} " EMAIL_ADDRESS
if [[ "$EMAIL_ADDRESS" =~ .*@.*\..* ]];then
    echo -e "\n${GREEN}Email address is valid.${COLOR_RESET}"
else
    echo -e "\n${RED}Email address is invalid${COLOR_RESET}"
    exit 1
fi
checkDomain
}

getUsername() {
read -e -p "Enter a username (or forwarding email): " USERNAME
}

checkDomain() {
DOMAIN=`echo $EMAIL_ADDRESS|awk -F'@' '{print $2}'`
digMojo=`dig @ns1.mojohost.com +short mx $DOMAIN|sort -n|head -1|awk '{print $NF}'|sed 's/.$//'`
digGoogle=`dig @8.8.8.8 +short mx $DOMAIN|sort -n|head -1|awk '{print $NF}'|sed 's/.$//'`

if [[ -z "$digMojo" ]];then
    echo -e "${RED}"
    read -p "Could not find an MX record for ${DOMAIN}. Continue anyway?[y/N] " IGNORE_NO_DNS
    echo -e "${COLOR_RESET}"
    case $IGNORE_NO_DNS in
        [yY] | [yY][Ee][Ss] ) echo "Carry on.";;
                           *) echo "Quitting...";exit 1;;
    esac
elif [[ ! "$digMojo" == $digGoogle ]];then
    read -e -p "${BOLD}This MAY not be the right server. Continue anyway?[y/N]:${NORMAL} " IGNORE_DNS_MISMATCH
    case $IGNORE_DNS_MISMATCH in
        [yY] | [yY][Ee][Ss] ) echo "Carry on.";;
                           *) echo "Quitting...";exit 1;;
    esac
else
    IP_CHECK=`dig @ns1.mojohost.com +short $digMojo|head -1`
    if [[ -z `ifconfig|grep $IP_CHECK` ]];then
    echo -e "\n${RED}WARNING!"
    read -p "${digMojo} probably doesn't resolve here. Continue anyway?[y/N]: " IGNORE_WRONG_SERVER
    echo -e "${COLOR_RESET}"
    case $IGNORE_WRONG_SERVER in
        [yY] | [yY][Ee][Ss] ) echo "Carry on.";;
                           *) echo "Quitting...";exit 1;;
    esac
    fi
fi
}

listEmails() {
if [[ ! -e $USER_FILE ]];then
    echo -e "\n${RED}Cannot find $USER_FILE."
    exit 1
fi
printf "\nAny existing mailboxes will be listed below.\n\n"
egrep -v ^# $USER_FILE
printf "\n"
}

listAliases() {
if [[ ! -e $ALIAS_FILE ]];then
    echo -e "\n${RED}Cannot find $ALIAS_FILE."
    exit 1
fi
printf "\nAny existing aliases will be listed below.\n\n"
egrep -v ^# $ALIAS_FILE|egrep -v ^$|grep -wv root|grep -wv postmaster|grep -wv webmaster|grep -wv ftp|grep -wv news
}

addEmail() {
getEmailAddress && getUsername
echo "$DOMAIN $USER_FILE $USERNAME"
if [[ -z `grep $DOMAIN $USER_FILE` ]];then
    printf "\n${EMAIL_ADDRESS}\t${USERNAME}" >> $USER_FILE
else
    LAST_LINE=`grep $DOMAIN $USER_FILE|tail -1|awk '{print $NF}'`
    sed -i -e "0,/${LAST_LINE}$/s//${LAST_LINE}\n${EMAIL_ADDRESS}\t${USERNAME}/" $USER_FILE
fi
addLocalUser
}

addAlias() {
echo "not yet working" && exit

# Here's a start.
getEmailAddress && getUsername
echo "Add alias code here."
}

addLocalUser() {
if [[ ! "$USERNAME" =~ .*@.*\..* ]];then
    useradd -s /bin/false $USERNAME
    PASSWORD=`cat /dev/urandom| tr -dc "a-zA-Z0-9${spec}" | fold -w 8 |head -1`
    echo "$PASSWORD"|passwd $USERNAME --stdin
    serverRestart && printCredentials
else
    serverRestart
    printf "\n${GREEN}$EMAIL_ADDRESS now forwards to $USERNAME.${COLOR_RESET}\n"
fi
}

testEmail() {
echo "Add test email code here."
}

serverRestart() {
cd /etc/mail
/usr/bin/makemap hash virtusertable < /etc/mail/virtusertable
newaliases
service sendmail restart
}

printCredentials() {
printf "\
\n${BOLD}Now for the moment we've all been waiting for...\n\
${GREEN}$EMAIL_ADDRESS\n\
Incoming/Outgoing server: $HOSTNAME\n\
Ports: 110 (POP) 25 (SMTP)\n\
Username: $USERNAME\n\
Password: $PASSWORD\n\
${COLOR_RESET}${NORMAL}\n"
}

if [[ `whoami` != "root" ]];then
    echo "This script must be run as root."
    exit 1
fi

if [[ -z `pidof sendmail` ]];then
    echo -e "\n${RED}Cannot continue. Is sendmail running?${COLOR_RESET}"
    exit 1
fi

printf "\nSelect an option below.\n\n\
1) List current emails\n\
2) List current aliases\n\
3) Create new email\n\
4) Create new alias\n\n"

read -e -p "${BOLD}Enter a number:${NORMAL} " SELECTION

case $SELECTION in
    1) listEmails;exit 0;;
    2) listAliases;exit 0;;
    3) addEmail;exit 0;;
    4) addAlias;exit 0;;
    *) echo -e "\nNext time, make a valid selection.";exit;;
esac
